﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using CRC.Inspecciones.Dominio.Controlador;

namespace CRC.Inspecciones.Presentacion
{
    public partial class FrmListadoImpresos : System.Windows.Forms.Form 
    {

        private IList<Object[]> _lstImpresos;
        private CtrlImpreso _ctrlImp = null;
        private CtrlZona _ctrlZona = null;
        
        public FrmListadoImpresos()
        {
            InitializeComponent();
        }

        private void UsrListadoImpresos_Load(object sender, EventArgs e)
        {
            _ctrlImp = new CtrlImpreso();
            _ctrlZona = new CtrlZona();

            CargarFiltros();
            CargarListado();
        }

        #region " Carga listado "

        private void CargarFiltros() {

            try {

                 for (int i = 2007; i < 2100; i++)
                     CmbAno.Items.Add(i);

                 CmbAno.SelectedItem = DateTime.Today.Year;
                CmbAno.SelectedIndexChanged+=new EventHandler(CmbAno_SelectedIndexChanged);

                CmbTipoImpreso.SetData(_ctrlImp.listarTiposImpreso());
                if (CmbTipoImpreso.Items.Count > 0) CmbTipoImpreso.SelectedIndex = 0;
                CmbTipoImpreso.SelectedIndexChanged+=new EventHandler(CmbTipoImpreso_SelectedIndexChanged);

                CmbZona.SetData(_ctrlZona.ObtenerZonas());
                if (CmbZona.Items.Count>0) CmbZona.SelectedIndex = 0;
                CmbZona.SelectedIndexChanged+=new EventHandler(CmbZona_SelectedIndexChanged);

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void CargarListado() {

            int? ano = (int?)CmbAno.SelectedItem;
            int? zona = (int?)CmbZona.SelectedKey;
            String codigoImp = (String)CmbTipoImpreso.SelectedItem; 

                 statusStrip1.Items[0].Text = "Cargando datos ...";
                 anadirToolStripMenuItem.Enabled = false;
                 refrescarToolStripMenuItem.Enabled = false;
                 eliminarToolStripMenuItem.Enabled = false;
                dataGridView1.Enabled = false;

                backgroundWorker1.RunWorkerAsync(new Object[] { ano, codigoImp, zona });
           
        }

        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            Object[] args = (Object[])e.Argument;
            e.Result = _ctrlImp.listarImpresos((int?)args[0], (String)args[1], (int?)args[2]);
        }

        private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            try {
                if (e.Error != null) {
                        MessageBox.Show(e.Error.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        statusStrip1.Items[0].Text = "Error: " + e.Error.Message;
                        return;
                    } 
                    _lstImpresos = (IList<Object[]>)e.Result;
                    LlenarListado(_lstImpresos);

                    statusStrip1.Items[0].Text = _lstImpresos.Count.ToString() + " impresos." ;

            }
            finally
            {
                anadirToolStripMenuItem.Enabled = true;
                refrescarToolStripMenuItem.Enabled = true;
                eliminarToolStripMenuItem.Enabled = true;
                dataGridView1.Enabled = true;
            }
                
        }

        private void LlenarListado(IList<Object[]> pLstImpresos)
        {
            dataGridView1.Rows.Clear();

            int i = 0;
            foreach (Object[] infImpreso in pLstImpresos)
            {
                dataGridView1.Rows.Add(infImpreso);
                if ((bool)infImpreso[4]) // Si es borrador resalta el color de la fila
                {
                    dataGridView1.Rows[i].DefaultCellStyle.BackColor = Color.LightSalmon;
                    dataGridView1.Rows[i].Cells["Ver"].Value = "Editar borrador";
                }
                else
                {
                    dataGridView1.Rows[i].Cells["Ver"].Value = "Ver";
                    dataGridView1.Rows[i].DefaultCellStyle.BackColor = Color.Honeydew;
                }
                i++;
            }
        }

        private void CmbTipoImpreso_SelectedIndexChanged(object sender, EventArgs e)
        {
            CargarListado();
        }

        private void CmbAno_SelectedIndexChanged(object sender, EventArgs e)
        {
            CargarListado();
        }

        private void CmbZona_SelectedIndexChanged(object sender, EventArgs e)
        {
            CargarListado();
        }

        #endregion

        /// <summary>
        /// Handler para editar o ver un impreso
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (dataGridView1.Columns["Ver"].Index == e.ColumnIndex) 
            {
                int id = (int)dataGridView1.Rows[e.RowIndex].Cells["Id"].Value;
                FrmImpreso usrTO34 = new FrmImpreso(id);
                usrTO34.Show();
            }
        }

        private void BtnanadirImpreso_Click(object sender, EventArgs e)
        {
            AnadirNuevoImpreso();
        }

        private void AnadirNuevoImpreso() { 
             DlgAnadirImpreso dlgAnImp = new DlgAnadirImpreso();
                if (dlgAnImp.ShowDialog() == DialogResult.OK) 
                {
                    StringBuilder html = new StringBuilder();

                    try
                    {
                        CRC.Inspecciones.Dominio.Clases.Impreso imp = _ctrlImp.nuevoImpreso(dlgAnImp.CodigoImpreso, dlgAnImp.IdSalon, html);
                        toolStripStatusLabel1.Text = "Impreso creado correctamente";
                        dataGridView1.Rows.Add(new Object[] { imp.Id, dlgAnImp.CodigoImpreso, imp.FechaConstruccion, imp.SalonInspeccionado.Nombre_Salon, null});
                        
                        switch (dlgAnImp.CodigoImpreso) { 
                            case "TO-34":
                                FrmImpreso TO34 = new FrmImpreso(imp.Id);
                                TO34.Show();
                            break;
                        }
                    }
                    catch (Exception ex) {
                        MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
        }

        private void ButEliminar_Click(object sender, EventArgs e)
        {
            EliminarImpreso();
        }


        private void EliminarImpreso() {
            if (MessageBox.Show(
                     "¿Estás seguro de quieres eliminar este impreso?", "Confirmar",
                     MessageBoxButtons.YesNo, MessageBoxIcon.Question
                 ) == DialogResult.Yes)
            {
                if (dataGridView1.SelectedRows.Count > 0)
                {
                    try
                    {
                        int iImp = (int)dataGridView1.SelectedRows[0].Cells["Id"].Value;
                        _ctrlImp.eliminarImpreso(iImp);
                        dataGridView1.Rows.Remove(dataGridView1.SelectedRows[0]);
                        toolStripStatusLabel1.Text = "Impreso eliminado correctamente";
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(
                            ex.Message, "Error",
                            MessageBoxButtons.OK, MessageBoxIcon.Warning
                        );
                    }
                }
            }
        }

        private void anadirToolStripMenuItem_Click(object sender, EventArgs e)
        {
            AnadirNuevoImpreso();
        }

        private void eliminarToolStripMenuItem_Click(object sender, EventArgs e)
        {
            EliminarImpreso();
        }

        private void refrescarToolStripMenuItem_Click(object sender, EventArgs e)
        {
            CargarListado();
        }

    }
    }
